package com.nbstar.film.spider.font.woff;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: wangxindong
 * @date: 2018/8/30-20:30
 */
public abstract class AbstractWoffTable {

	protected static final Logger LOGGER = LoggerFactory.getLogger(AbstractWoffTable.class);

	protected String tag;
	protected int offset;
	protected int compLength;
	protected int origLength;
	protected int origChecksum;

	private WoffFont woffFont;

	protected AbstractWoffTable(WoffFont woffFont) {
		this.woffFont = woffFont;
	}

	/**
	 * 子类需要实现此方法，来进行表的数据读取逻辑
	 *
	 * @param woffFont
	 * @param stream
	 * @throws IOException
	 */
	public abstract void read(WoffFont woffFont, AbstractOTFDataStream stream) throws IOException;

	/**
	 * 解压数据
	 *
	 * @param fontData
	 * @param
	 * @return
	 */
	protected byte[] inflateFontData(byte[] fontData) {
		byte[] inflatedFontData;
		if (compLength != origLength) {
			inflatedFontData = new byte[origLength];
			Inflater decompressor = new Inflater();
			decompressor.setInput(fontData, 0, compLength);
			try {
				decompressor.inflate(inflatedFontData, 0, origLength);
			} catch (DataFormatException e) {
				LOGGER.error("Malformed woff file {}", e);
			}
		} else {
			inflatedFontData = fontData;
		}
		return inflatedFontData;
	}

	/**
	 * 计算表的校验值
	 *
	 * @author: Wang Xindong
	 */
	protected int calcTableChecksum() {
		int sum = 0;
		
		
		return 0;
	}

	public String getTag() {
		return tag;
	}

	public void setTag(String tag) {
		this.tag = tag;
	}

	public int getOffset() {
		return offset;
	}

	public void setOffset(int offset) {
		this.offset = offset;
	}

	public int getCompLength() {
		return compLength;
	}

	public void setCompLength(int compLength) {
		this.compLength = compLength;
	}

	public int getOrigLength() {
		return origLength;
	}

	public void setOrigLength(int origLength) {
		this.origLength = origLength;
	}

	public int getOrigChecksum() {
		return origChecksum;
	}

	public void setOrigChecksum(int origChecksum) {
		this.origChecksum = origChecksum;
	}

	@Override
	public String toString() {
		return "AbstractWoffTable{" + "tag='" + tag + '\'' + ", offset=" + offset + ", compLength=" + compLength
				+ ", origLength=" + origLength + ", origChecksum=" + origChecksum + ", woffFont=" + woffFont + '}';
	}
}
